var DB = require('./db');
var ObjectID = require('mongodb').ObjectID;

function Article(article) {

    //数据库id
    this._id = article._id;

    //标题
    this.title = article.title || "";

    //简介
    this.abstract = article.abstract || "";

    //分类
    this.category = article.category || "其他";

    //内容
    this.content = article.content || "";

    //发表时间
    this.insertTime = article.insertTime || "";

}

//插入一条Article数据
Article.prototype.insert = function (callback) {

    var _this = this;
    DB.connect(function (err, db) {
        if (err) {
            return callback(err, {});
        }

        var newArticle = {
            "title": _this.title,
            "abstract": _this.abstract,
            "category": _this.category,
            "content": _this.content,
            "insertTime": _this.insertTime
        };

        var collection = db.collection('article');
        collection.insertOne(newArticle, function (err, doc) {
            db.close();
            return callback(err, doc);
        })
    })
}

//更新一条数据
Article.prototype.update = function (callback) {

    var _this = this;
    DB.connect(function (err, db) {
        if (err) {
            return callback(err, {});
        }

        var updateArticle = {
            "_id": ObjectID(_this._id),
            "title": _this.title,
            "abstract": _this.abstract,
            "category": _this.category,
            "content": _this.content,
            "insertTime": _this.insertTime
        };
        var collection = db.collection('article');
        collection.save(updateArticle, function (err, doc) {
            db.close();
            return callback(err, doc);
        })
    });
}

/**
 *
 * */
Article.findOne = function (_id, callback) {
    var _this = this;
    DB.connect(function (err, db) {
        if (err) {
            return callback(err, {});
        }
        var collection = db.collection('article');
        collection.findOne({_id: ObjectID(_id)}, function (err, doc) {
            db.close();
            return callback(err, doc);
        });
    })
}

/**
 *  按分页查询数据
 *
 *  返回的结果为：
 *    returnpage: {
 *      list       -- 数据列表
 *      prevpage   -- 前一页
 *      nextpage   -- 后一页
 *      pageNumber -- 当前页
 *      keyword    -- 关键字
 *    }
 *
 * */
Article.list = function (page, callback) {

    var queryOption = {};
    var keywordArray = [];

    //如果关键词不为空
    if (page.keyword && page.keyword !== '') {
        var regexp = new RegExp(page.keyword);
        keywordArray = [{"title": regexp},{"abstract": regexp}];
        queryOption['$or'] = keywordArray;
    }

    //如果分类不为空
    if (page.category && page.category !== '') {
        queryOption['category'] = page.category;
    }

    var total = 0;

    //当前是第几页
    var pageNumber = parseInt(page.pageNumber) || 1;

    //每页有几个
    var perNumber = parseInt(page.perNumber) || 10;

    //要跳过的数目
    var skipNumber = (pageNumber - 1) * perNumber;

    DB.connect(function (err, db) {
        if (err) {
            return callback(err, {});
        }

        var collection = db.collection('article');
        collection.count(queryOption, function (err, count) {
            if (err) {
                return callback(err, {});
            }
            total = count;
            collection.find(queryOption, {"content": 0})
                .sort({"_id": 1})
                .skip(skipNumber)
                .limit(perNumber)
                .toArray(function (err, docs) {
                    db.close();
                    if (docs.length) {
                        var returnPage = {};

                        returnPage.list = docs;
                        returnPage.pageNumber = pageNumber;
                        returnPage.keyword = queryOption.keyword;
                        returnPage.category = queryOption.category;

                        //如果当前为第一页的话，前一页为空
                        returnPage.prevpage = (pageNumber == 1) ? null : pageNumber - 1;

                        //总页数，如果当前页等于总页数的话，下一页则为空
                        var totalpage = Math.ceil(total/perNumber);
                        if (pageNumber == totalpage) {
                            returnPage.nextpage = null;
                        } else {
                            returnPage.nextpage = pageNumber + 1;
                        }

                        return callback(err, returnPage);

                    } else {
                        var returnPage = {};
                        returnPage.pageNumber = 1;
                        returnPage.keyword = queryOption.keyword;
                        returnPage.category = queryOption.category;
                        returnPage.prevpage = null;
                        returnPage.nextpage = null;
                        returnPage.list = {};
                        return callback(err, returnPage);
                    }
                })
            ;
        });
    })
}

Article.remove = function (_idList, callback) {

    var removeList = _idList.map(function (_id) {
        _id = ObjectID(_id);
        return _id;
    });

    DB.connect(function (err, db) {
        if (err) {
            return callback(err, null);
        }

        var collection = db.collection('article');
        collection.remove({"_id": {"$in": removeList}}, function (err, result) {
            return callback(err, result);
        });
    })

}

module.exports = Article;